#!/usr/bin/python
#encoding: utf-8

import os
import fcntl
import traceback


class ExistError(Exception):
    """'Another instance is exist"""
    pass


class CSingleInstance(object):
    """ Implements single instance on one machine """
    
    def __init__(self,pid_file):
        """ Constructor. There results：
        1. raise IOError：failed to open pid_file for write.
        2. raise ExistError：Another instance is exist.
        3. No exception：I'm the only instance!
        """
        self._pid_file = pid_file
        self._fp = None

        fp = open(pid_file,'w')

        try:
            fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except IOError:
            fp.close()
            raise ExistError('Another instance is exist')

        try:
            fp.write(str(os.getpid()))
            fp.flush()
        except:
            pass

        self._fp = fp;


    def __del__(self):
        """ Free resources """
        try:
            fp = self._fp
            if fp:
                fcntl.lockf(fp,fcntl.LOCK_UN)
                fp.close()
                os.unlink(self._pid_file)
        except:
            pass


if __name__ == '__main__':
    import time
    si = CSingleInstance('/tmp/test.pid')

    while True:
        print 'No one but me,hahaha~~'
        time.sleep(1)

